<template>
  <div class="nav-bar-container">
    <el-row :gutter="15">
      <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
        <div class="left-panel">
          <i :class="collapse ? 'el-icon-s-unfold' : 'el-icon-s-fold'" :title="collapse ? '展开' : '收起'" class="fold-unfold"
            @click="handleCollapse"></i>
          <vab-breadcrumb class="hidden-xs-only" />
        </div>
      </el-col>
      <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
        <div class="bs-sysMsg" v-if="leaderShow">
          <p class="tips-sysMsg"><i class="el-icon-bell"></i>上报信息：</p>
          <div class="msg__content">
            <el-carousel height="20px" direction="horizontal" :interval="4000" indicator-position="none" :autoplay="true">
              <el-carousel-item v-for="item in systemMsg" :key="item.id">
                <a href="javascript:void(0)" class="item" @click="leaderSee(item)">【{{ item.title }}】{{ item.name }}</a>
                <!--                <p class="item">【{{item.title}}】{{item.name}}</p>-->
              </el-carousel-item>
            </el-carousel>
          </div>
        </div>
        <div v-else>&nbsp;&nbsp;</div>
      </el-col>
      <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
        <div class="right-panel">
          <!-- <vab-error-log /> -->
<!--          <el-button @click="speak">播放</el-button>-->
          <vab-full-screen-bar @refresh="refreshRoute" />
          <vab-theme-bar class="hidden-xs-only" />
          <vab-icon title="重载所有路由" :pulse="pulse" :icon="['fas', 'redo']" @click="refreshRoute" />
          <vab-avatar />
          <!--  <vab-icon
            title="退出系统"
            :icon="['fas', 'sign-out-alt']"
            @click="logout"
          />-->
        </div>
      </el-col>
    </el-row>
    <el-dialog title="密码修改" :visible.sync="dialogFormVisible" width="600px" :close-on-click-modal="false" @close="close" append-to-body>
      <div class="pass-tips"><i class="el-icon-warning"></i><span>当前密码强度弱，为保障您的账户安全请您尽快修改密码！</span></div>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="旧密码" prop="oldPass">
              <el-input v-model.trim="form.oldPass" autocomplete="off" type="password"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="新密码" prop="newPass">
              <el-input v-model.trim="form.newPass" autocomplete="off" type="password"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="确认密码" prop="confirmPass">
              <el-input v-model.trim="form.confirmPass" autocomplete="off" type="password"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">

        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="save" :disabled="this.isDisable">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Speech from 'speak-tts'
import { mapActions, mapGetters } from 'vuex'
import { getLeaderList, readLeader } from '@/api/warningOrderLeader'
import {getFirstList, getList} from "@/api/sysNotice";
import {updatePass} from "@/api/user";
import {recordRoute} from "@/config/setting.config";
export default {
  name: 'VabNavBar',
  data() {
    return {
      pulse: false,
      systemMsg: [

      ],
      leaderShow: true,
      timers: '',
      speech: null,
      isDisable: false,
      form: {
        oldPass: '',
        newPass: '',
        confirmPass: '',
        userId: '',
      },
      rules: {
        oldPass: [{ required: true, trigger: 'blur', message: '请输入密码' }],
        newPass: [
          { required: true, trigger: 'blur', message: '请输入新密码', min: 6, message: '密码不能少于6位' },
        ],
        confirmPass: [{ required: true, trigger: 'blur', message: '请输入确认密码', min: 6, message: '密码不能少于6位' }],

      },
      dialogFormVisible: false,
    }
  },
  created() {
    this.getLeaderListInfo();
    this.getFirstNoticeList();
    this.getWeekPass();
  },
  mounted() {
    this.speechInit();
    const timers = setInterval(() => {   // 在页面加载后开启一个定时器
      this.getLeaderListInfo();
      this.getNoticeList();
    }, 60000)

    this.$once('hook:beforeDestroy', () => {   //再通过事件监听，监听到 组件销毁 后，再执行关闭计时器。
      clearInterval(timers);
    })
  },
  computed: {
    ...mapGetters({
      collapse: 'settings/collapse',
      visitedRoutes: 'tabsBar/visitedRoutes',
      device: 'settings/device',
      routes: 'routes/routes',
    }),
  },
  methods: {
    ...mapActions({
      changeCollapse: 'settings/changeCollapse',
    }),
    speechInit() {
      this.speech = new Speech();
      if (this.speech.hasBrowserSupport()) { // returns a boolean
        console.log("speech synthesis supported")
      }

      this.speech.setLanguage('zh-CN');
      this.speech.init().then(() => {
        console.log('语音播报初始化完成...')
      }).catch(e => {
        console.error("An error occured while initializing : ", e)
      })

    },

    //语音播报
    speak(txt) {
      //console.log("播报开始...")
      // this.speech.speak({ text: "您有新的短消息，请及时处理" }).then(() => {
      //   console.log("播报完成...")
      // })
      this.speech.speak({
        text: txt,
      }).then(() => {
        console.log("播报完成...")
      }).catch(e => {
        console.error("播报错误:", e)
      })

    },
    handleCollapse() {
      this.changeCollapse()
    },
    async refreshRoute() {
      this.$baseEventBus.$emit('reload-routerview')
      this.pulse = true
      setTimeout(() => {
        this.pulse = false
      }, 1000)
    },
    leaderSee(val) {
      var id = val.id;
      readLeader(id).then((res) => {
        console.log('res', res);
        if (res.code == 0) {
          this.getLeaderListInfo();
          //跳转警令
          if (val.discriminate == 0) {
            this.$router.push({
              path: '/myjl/jlgl', query: { name: val.name }
            })
          }
          //跳转警情
          if (val.discriminate == 1) {
            this.$router.push({
              path: '/myjq/jqgl', query: { name: val.name }
            })
          }
        } else {
          this.$baseMessage('请手动跳转', 'error')
        }

      })
    },
    getLeaderListInfo() {
      getLeaderList().then((res) => {
        console.log('getLeaderList', res)
        var list = res.data;
        if (list.length == 0) {
          this.systemMsg = [];
          this.leaderShow = false;

        } else {
          this.leaderShow = true;
          this.systemMsg = [];
          for (var i = 0; i < list.length; i++) {
            var x = {};
            x.id = list[i].warning_order_id;
            x.name = list[i].name;
            if (list[i].discriminate == 1) {
              x.title = '警情上报';
            }
            if (list[i].discriminate == 0) {
              x.title = '警令上报';
            }
            x.discriminate = list[i].discriminate;
            this.systemMsg.push(x)
          }
        }
      })
    },
    getNoticeList(){
      getList().then((res) => {
        if (res.code === 0){
          var list = res.data;
          if (list){
            for (var i= 0 ; i < list.length ; i++){
              this.speak(list[i].content)
            }
          }
        }
      })
    },
    getFirstNoticeList(){
      getFirstList().then((res) => {
        if (res.code === 0){
          var list = res.data;
          if (list){
            for (var i= 0 ; i < list.length ; i++){
              this.speak(list[i].content)
            }
          }
        }
      })
    },

    getWeekPass(){
      var val = localStorage.getItem("weekPass");
      console.log(val);
      if (val === '0'){
        this.dialogFormVisible = true
      }
    },
    close() {
      this.$refs['form'].resetFields()
      this.form = this.$options.data().form
      this.dialogFormVisible = false
    },
    async save() {
      var reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{6,20}$/
      if (!reg1.test(this.form.newPass)){
        this.$baseMessage('密码必须包含大小写字母和数字的组合，不能使用特殊字符，长度在 6-20 之间', 'error');
        return;
      }

      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          this.isDisable = true;
          console.log(this.form)
          const data = await updatePass(this.form)
          console.log(data);
          if (data.code == 0) {
            this.$baseMessage('修改成功', 'success');
            localStorage.setItem("weekPass",1)
            await this.$store.dispatch('user/logout')
            if (recordRoute) {
              this.delAllVisitedRoutes();//清除tabs
              const fullPath = this.$route.fullPath
              // this.$router.push(`/login?redirect=${fullPath}`)
              this.$router.push('/login')
              this.reload()
            } else {
              this.$router.push('/login')
              this.reload()
            }
          } else {
            this.$baseMessage(data.msg, 'error');
            this.isDisable = false;
          }
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.nav-bar-container {
  position: relative;
  height: $base-nav-bar-height;
  padding-right: $base-padding;
  padding-left: $base-padding;
  overflow: hidden;
  user-select: none;
  background: $base-color-white;
  box-shadow: $base-box-shadow;

  .left-panel {
    display: flex;
    align-items: center;
    justify-items: center;
    height: $base-nav-bar-height;

    .fold-unfold {
      color: $base-color-gray;
      cursor: pointer;
    }

    ::v-deep {
      .breadcrumb-container {
        margin-left: 10px;
      }
    }
  }

  .right-panel {
    display: flex;
    align-content: center;
    align-items: center;
    justify-content: flex-end;
    height: $base-nav-bar-height;

    ::v-deep {
      svg {
        width: 1em;
        height: 1em;
        margin-right: 15px;
        font-size: $base-font-size-small;
        color: $base-color-gray;
        cursor: pointer;
        fill: $base-color-gray;
      }

      button {
        svg {
          margin-right: 0;
          color: $base-color-white;
          cursor: pointer;
          fill: $base-color-white;
        }
      }

      .el-badge {
        margin-right: 15px;
      }
    }

  }
}

.bs-sysMsg {
  position: relative;
  display: flex;
  width: 100%;
  margin-top: 10px;
  padding: 8px 6px;
  background-color: #fffbe8;
  overflow: hidden;
  opacity: 1;
  transition: opacity 0.2s;
}

.bs-sysMsg .tips-sysMsg {
  padding: 0 0 0 10px;
  margin: 0;
  line-height: 24px;
  color: #ed6a0c;
}

.bs-sysMsg .tips-sysMsg i {
  margin-right: 2px;
}

.bs-sysMsg .msg__content {
  padding: 0 8px;
  flex: 1;
}

.bs-sysMsg .msg__content a.item {
  color: #ed6a0c;
  font-size: 14px;
  line-height: 24px;
}

.bs-sysMsg .msg__content a.item:hover {
  text-decoration: underline;
}
.pass-tips{
  display: inline-block;
  height: 32px;
  padding: 0 10px;
  line-height: 30px;
  font-size: 14px;
  border-radius: 4px;
  box-sizing: border-box;
  background-color: #fef0f0;
  border-color: #fde2e2;
  color: #f56c6c;
  margin-bottom: 20px;
  margin-left: 100px;
  i{
    margin-right: 4px;
  }
}
</style>
